package com.gx.rabbit.config;

import com.gx.common.constant.RabbitMqConstant;
import com.gx.rabbit.consumer.FanoutConsumer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.gx.common.constant.RabbitMqConstant.FANOUT_QUERY_SYS_BAK;

/**
 * @Author Liu-pj
 * @Date 2023/3/9 15:41
 * @Desc 系统备份消息 fanout 广播模式
 **/
@Configuration
public class FanoutConf {
    private final RabbitProperties rabbitProperties;

    public FanoutConf(RabbitProperties rabbitProperties) {
        this.rabbitProperties = rabbitProperties;
    }

    @Bean
    public FanoutExchange exchangeSysBak() {
        return new FanoutExchange(RabbitMqConstant.FANOUT_EXCHANGE_SYS_BAK);
    }

    @Bean
    public Queue queueSysBak() {
        return QueueBuilder.durable(FANOUT_QUERY_SYS_BAK)
                .build();
    }


    @Bean
    public Binding sysBakExBindingSysBakQueue() {
        return BindingBuilder.bind(queueSysBak())
                .to(exchangeSysBak());
    }

    @Bean
    public SimpleMessageListenerContainer sysBakConsumerListenerContainer(ConnectionFactory connectionFactory,
                                                                          @Qualifier("fanoutConsumer") FanoutConsumer fanoutConsumer) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames(FANOUT_QUERY_SYS_BAK);
        buildMessageListenerContainer(container);
        container.setMessageListener(fanoutConsumer);
        return container;
    }

    private void buildMessageListenerContainer(SimpleMessageListenerContainer messageListenerContainer) {
        messageListenerContainer.setExposeListenerChannel(true);
        messageListenerContainer.setAcknowledgeMode(rabbitProperties.getListener().getSimple().getAcknowledgeMode());
        messageListenerContainer.setPrefetchCount(rabbitProperties.getListener().getSimple().getPrefetch());
        messageListenerContainer.setConcurrentConsumers(rabbitProperties.getListener().getSimple().getConcurrency());
        messageListenerContainer.setMaxConcurrentConsumers(rabbitProperties.getListener().getSimple().getMaxConcurrency());
    }
}
